package com.zmkj.cn.comm.util;

import com.zmkj.cn.comm.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
 * XML文件处理工具类
 * @author 伍绍宇 Coy
 * @date 2021年4月19日 11:30:16
 */
@Slf4j
public class MyXmlUtil {

    public static String xmlChangeString(String fileName) {
        try {
            // 新建一个解析类
            SAXReader saxReader = new SAXReader();
            Document tempDocument = saxReader.read(new File(fileName));
            return tempDocument.asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将字符串string类型转换成xml文件
     * @author 伍绍宇 Coy
     * @date 2021年4月19日 11:30:16
     */
    public static void strChangeXml(String str,String fileName){
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            document = saxReader.read(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)));
            OutputFormat format = OutputFormat.createPrettyPrint();
            /** 将document中的内容写入文件中 */
            File file=  new File(fileName);
            MyFileUtil.createFileDir(file.getParent());
            XMLWriter writer = new XMLWriter(new FileWriter(file),format);
            writer.write(document);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("字符串转XML失败","字符串转XML失败",-1);
        }
    }


    /**
     * 获取jdom解析器
     * 
     */
    public static   org.w3c.dom.Document  getDocument(MultipartFile file){
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //通过工厂对象创建一个DOM解析器对象
        DocumentBuilder documentBuilder = null;
        org.w3c.dom.Document parse =null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream resourceAsStream =file.getInputStream();
            //此代码完成后,整个XML文档已经被加载到内存中,以树状形式存储;
            parse = documentBuilder.parse(resourceAsStream);
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
        return  parse;
    }


    /**
     * 获取jdom解析器
     * 
     */
    public static   org.w3c.dom.Document  getDocumentByFile(File file){
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //通过工厂对象创建一个DOM解析器对象
        DocumentBuilder documentBuilder = null;
        org.w3c.dom.Document parse =null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream resourceAsStream =new FileInputStream(file);
            //此代码完成后,整个XML文档已经被加载到内存中,以树状形式存储;
            parse = documentBuilder.parse(resourceAsStream);
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
        return  parse;
    }




    public static org.w3c.dom.Document stringToXml(String str) {

        StringBuilder sxml = new StringBuilder();
        sxml.append(str);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        org.w3c.dom.Document doc = null;
        try {
            InputStream is = new ByteArrayInputStream(sxml.toString().getBytes("utf-8"));
            doc = dbf.newDocumentBuilder().parse(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }


    /**
     *
     * @param document
     *            Document对象（读xml生成的）
     * @return String字符串
     */
    public static String xmlToString(org.w3c.dom.Document document) {
        TransformerFactory ft = TransformerFactory.newInstance();
        try {
            Transformer ff = ft.newTransformer();
            ff.setOutputProperty("encoding", "UTF-8");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ff.transform(new DOMSource(document), new StreamResult(bos));
            return bos.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return "";
    }

}
